const app = getApp()
import { request } from "../../request/index.js"
import { navigateTo, uploadFile } from "../../utils/asyncWx.js"
import { isNotEmptyStr,wxuuid } from "../../utils/util.js"
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const defaultNickName = '微信用户'


Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    nickName: "",
    savedFilePath: ''
  },
  onLoad() {

  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    console.log(avatarUrl)
    // this.setData({
    //   avatarUrl,
    // })

    // 测试临时文件转本地文件  将图片的路径更新为本地路径
    let fsm = wx.getFileSystemManager()
    let savedFilePath = fsm.saveFileSync(avatarUrl)

    console.log("saveFilePath>>>>>  ", savedFilePath)
    this.setData({ avatarUrl: savedFilePath })
  },
  // 用户输入完点击软键盘的确定后执行的函数
  bindKeyInput(e) {
    let { value } = e.detail
    console.log(value)
    this.setData({ nickName: value })
    wx.setStorageSync('nickName', value) // 存入缓存
  },
  // 用户点击提交后执行的函数
  async submit() {  // 聚合图床
    // 这里将本地文件上传至图床，得到图片的网络地址，将网络地址传至后端数据库
    let token = "38d09372267a4dd1b530488121def27e"
    let url = "https://api.superbed.cn/upload"
    let params = {
      filePath: this.data.avatarUrl,
      url,
      formData: { token }
    }
    const res = await uploadFile(params)
    console.log("图片上传成功!")
    let response = JSON.parse(res.data)
    let src = response.url
    this.setData({ avatarUrl: src })
    wx.setStorageSync('avatarUrl', src) // 存入缓存
    console.log(response);

    let data = {
      nickname: this.data.nickName,
      avatarUrl: this.data.avatarUrl
    }
    // 封装请求头
    let header = { "Content-Type": "application/x-www-form-urlencoded" }
    const result = await request({ url: "/WxUser/updateUser", data, header, method: "POST" })
    // 返回上一页
    wx.navigateBack({
      delta: 1
    })
  },

  async submit2() {  // 七牛图床
    // 获取uploadToken
    const result = await request({ url: "/Upload/getToken" })
    const uploadToken = result.data.data
    console.log(uploadToken)


    // 上传图片
    const uuid = wxuuid() // 设定每个图片的唯一标识符
    let param = {
      url: "https://up-z1.qiniup.com",
      filePath: this.data.avatarUrl,
      name: "file",
      header: { "Content-Type": "multipart/form-data" },
      formData: {
        key: `image/${uuid}`,
        token: uploadToken
      }
    }
    const response = await uploadFile(param)
    // console.log(response)

    const imageUrl = "http://cdn.pjm666.fun/image/" + uuid
    this.setData({ avatarUrl: imageUrl })
    wx.setStorageSync('avatarUrl', imageUrl) // 存入缓存

    let data = {
      nickName: this.data.nickName,
      avatarUrl: this.data.avatarUrl
    }
    // 封装请求头
    let header = { "Content-Type": "application/x-www-form-urlencoded" }
    await request({ url: "/WxUser/updateUser", data, header, method: "POST" })
    // 返回上一页
    wx.navigateBack({
      delta: 1
    })


  }
})
